package bigdata.hourglass.utils;

import bigdata.hourglass.exeception.HourglassException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization CC
 * @website https://www.jlpyyf.com
 * @date 2019/12/11 15:09
 * @since 1.0
 */
public class NetUtil {
    private static Logger logger = LoggerFactory.getLogger(NetUtil.class);
    private static final int MAX_PORT = 65535;

    public static int findAvailablePort(int defaultPort) {
        int portTmp = defaultPort;
        while (portTmp < MAX_PORT) {
            if (!isPortUsed(portTmp)) {
                return portTmp;
            } else {
                portTmp ++;
            }
        }
        portTmp = defaultPort - 1;
        while (portTmp > 0) {
            if (!isPortUsed(portTmp)) {
                return portTmp;
            } else {
                portTmp --;
            }
        }
        throw new HourglassException("no available port.");
    }

    /**
     * check port used
     *
     * @param port 端口号
     * @return 端口号是否被占用
     */
    public static boolean isPortUsed(int port) {
        boolean used;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            used = false;
        } catch (IOException e) {
            logger.info(">>>>>>>>>>> hourglass system, port[{}] is in use.", port);
            used = true;
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    logger.info("");
                }
            }
        }
        return used;
    }
}
